<template>
	<view>
		<!-- 加载状态 -->
		<view v-if="loading" class="loading-text">加载中...</view>

		<!-- 无数据提示 -->
		<view v-else-if="banners.length === 0" class="empty-text">暂无海报数据</view>

		<!-- 轮播图 -->
		<swiper v-else class="banner-container" indicator-dots autoplay interval="3000" duration="1000" circular>
			<swiper-item v-for="(item, index) in banners" :key="item._id || index" class="swiper-item"
				@click="handleBannerClick(item)">
				<image class="banner-image" :src="item.imagePath" mode="aspectFill" @error="handleImageError(index)">
				</image>
			</swiper-item>
		</swiper>
	</view>
</template>

<script setup>
	import {
		inject,
		ref
	} from 'vue'
	import {
		getBanner
	} from '../../api/homeApi'
	import {
		onLoad
	} from '@dcloudio/uni-app'

	const statusBarHeight = inject('statusBarHeight')

	// 状态变量
	const banners = ref([])
	const loading = ref(true)

	// 生命周期钩子
	onLoad(() => {
		fetchData()
	})

	// 获取接口数据
	const fetchData = async () => {
		try {
			const res = await getBanner()
			if (res?.data?.rows?.length) {
				banners.value = res.data.rows
			} else {
				console.warn('海报接口返回为空')
				banners.value = []
			}
		} catch (err) {
			console.error('获取海报失败:', err)
			uni.showToast({
				title: '加载海报失败',
				icon: 'none'
			})
			banners.value = []
		} finally {
			loading.value = false
		}
	}

	// 点击跳转逻辑
	const handleBannerClick = (item) => {
		if (item.open_type === 'navigate' && item.navigateUrl) {
			uni.navigateTo({
				url: item.navigateUrl
			})
		} else {
			console.log('点击了非跳转海报:', item)
		}
	}

	// 图片加载错误处理
	const handleImageError = (index) => {
		console.warn(`图片加载失败: ${banners.value[index].imagePath}`)
		banners.value[index].imagePath = '/static/default_banner.png' // 替换成你项目中的默认图片
	}
</script>

<style lang="scss" scoped>
	.banner-container {
		margin: 0 32rpx;
		height: 325rpx;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.swiper-item {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.banner-image {
		width: 682rpx;
		height: 304rpx;
		border-radius: 16rpx;
	}

	.loading-text,
	.empty-text {
		text-align: center;
		margin-top: 80rpx;
		color: #999;
		font-size: 28rpx;
	}
</style>